//
//  LLRefreshControl.swift
//  新浪微博
//
//  Created by mac on 16/5/30.
//  Copyright © 2016年 mac.com. All rights reserved.
//
import UIKit
import SnapKit
enum RefreshState: Int{
     case  Normal          //普通状态
     case  Pulling        //准备刷新
     case  Refreshing    //正在刷新
}
private var refreshViewHeigh: CGFloat = 60
class LLRefreshControl: UIControl {
    var statue: RefreshState = .Normal{
        didSet{
            switch statue {
            case .Normal:
//                print("下拉起飞")
                arrowIcon.hidden = false
                indicatorView.stopAnimating()
                tipLable.text = "下拉起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformIdentity
                })
                
            case .Pulling:
                tipLable.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.arrowIcon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
            case .Refreshing:
                print("正在起飞")
                arrowIcon.hidden = true
                indicatorView.startAnimating()
                tipLable.text = "正在起飞"
                //请求网络数据 给观察的对象主动发送对应类型的事件
                sendActionsForControlEvents(.ValueChanged)
//                sendActionsForControlEvents(.ValueChanged)
            }
        }
    }
    func endrefresh(){
    statue = .Normal
    
    }
    //键值观察的响应方法
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        //1.获取父视图的垂直方向的位移
        let offsetY = scrollView?.contentOffset.y ?? 0
        //2. 和 -124 比较
        
        //有被拽动
        if scrollView!.dragging {
            if statue == .Pulling && offsetY > -124 {
                //普通状态
                statue = .Normal
            } else if statue == .Normal && offsetY < -124  {
                //达到临界点 变为等待刷新状态
                statue = .Pulling
            }
        } else {
            //没有被拽动 && 并且状态是 等待刷新状态 修改为刷新状态
            if statue == .Pulling {
                statue = .Refreshing
            }
        }
        
    }
    //将要移动到父视图上
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //获取tableView
        if let myFather = newSuperview as? UIScrollView{
            //如果父视图是scrollView及其子类
            //获取父视图的垂直方向的位移
            // KVO  通过键值方式观察对象的属性变化
        scrollView = myFather
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    //移除键值观察
    deinit {
    scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshViewHeigh, width: ScreenWidth, height: refreshViewHeigh)
        super.init(frame: rect)
        backgroundColor = UIColor.yellowColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //设置界面
    private func setupUI() {
        addSubview(arrowIcon)
        addSubview(tipLable)
        addSubview(indicatorView)
        //设置约束
        arrowIcon.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        tipLable.snp_makeConstraints { (make) -> Void in
            make.left.equalTo(arrowIcon.snp_right)
            make.centerY.equalTo(self.snp_centerY)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    
    }
    //记录父视图的属性
    var scrollView: UIScrollView?
    //懒加载控件
    private lazy var arrowIcon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLable: UILabel = UILabel(title: "下拉起飞", font: 14, textColor: UIColor.darkGrayColor())
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
    
}
